"""
配置管理
"""
import os
from typing import Dict, Any, Optional
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings

from .constants import *


class EmbeddingSettings(BaseModel):
    """嵌入模型配置"""
    model_name: str = Field(default=DEFAULT_EMBEDDING_MODEL, description="嵌入模型名称")
    device: str = Field(default="cpu", description="计算设备")
    normalize: bool = Field(default=True, description="是否归一化向量")
    batch_size: int = Field(default=32, description="批处理大小")


class VectorStoreSettings(BaseModel):
    """向量存储配置"""
    type: str = Field(default=DEFAULT_VECTOR_STORE_TYPE, description="向量存储类型")
    storage_path: str = Field(default=DEFAULT_STORAGE_PATH, description="存储路径")
    
    # FAISS配置
    faiss_index_type: str = Field(default="Flat", description="FAISS索引类型")
    
    # Milvus配置
    milvus_host: str = Field(default="localhost", description="Milvus主机")
    milvus_port: int = Field(default=19530, description="Milvus端口")
    
    # PostgreSQL配置
    pg_connection_uri: str = Field(default="", description="PostgreSQL连接URI")
    
    # ChromaDB配置
    chroma_persist_directory: str = Field(default="./chroma_db", description="ChromaDB持久化目录")


class TextSplitterSettings(BaseModel):
    """文本分割配置"""
    chunk_size: int = Field(default=DEFAULT_CHUNK_SIZE, description="文本块大小")
    chunk_overlap: int = Field(default=DEFAULT_OVERLAP_SIZE, description="重叠长度")
    splitter_name: str = Field(default="ChineseRecursiveTextSplitter", description="分割器名称")
    zh_title_enhance: bool = Field(default=False, description="是否启用中文标题增强")


class SearchSettings(BaseModel):
    """搜索配置"""
    top_k: int = Field(default=DEFAULT_TOP_K, description="返回结果数量")
    score_threshold: float = Field(default=DEFAULT_SCORE_THRESHOLD, description="相似度阈值")
    search_type: str = Field(default="similarity", description="搜索类型")


class Settings(BaseSettings):
    """主配置类"""
    
    # 基础配置
    debug: bool = Field(default=False, description="调试模式")
    log_level: str = Field(default="INFO", description="日志级别")
    
    # 嵌入配置
    embedding: EmbeddingSettings = Field(default_factory=EmbeddingSettings)
    
    # 向量存储配置
    vector_store: VectorStoreSettings = Field(default_factory=VectorStoreSettings)
    
    # 文本分割配置
    text_splitter: TextSplitterSettings = Field(default_factory=TextSplitterSettings)
    
    # 搜索配置
    search: SearchSettings = Field(default_factory=SearchSettings)
    
    # API配置
    api_host: str = Field(default="0.0.0.0", description="API主机")
    api_port: int = Field(default=8000, description="API端口")
    
    class Config:
        env_file = ".env"
        env_nested_delimiter = "__"
    
    def get_vector_store_config(self) -> Dict[str, Any]:
        """获取向量存储配置"""
        config = {
            "type": self.vector_store.type,
            "storage_path": self.vector_store.storage_path,
        }
        
        if self.vector_store.type == "faiss":
            config.update({
                "index_type": self.vector_store.faiss_index_type,
            })
        elif self.vector_store.type == "milvus":
            config.update({
                "host": self.vector_store.milvus_host,
                "port": self.vector_store.milvus_port,
            })
        elif self.vector_store.type == "pg":
            config.update({
                "connection_uri": self.vector_store.pg_connection_uri,
            })
        elif self.vector_store.type == "chromadb":
            config.update({
                "persist_directory": self.vector_store.chroma_persist_directory,
            })
        
        return config
    
    def get_embedding_config(self) -> Dict[str, Any]:
        """获取嵌入模型配置"""
        return {
            "model_name": self.embedding.model_name,
            "device": self.embedding.device,
            "normalize": self.embedding.normalize,
            "batch_size": self.embedding.batch_size,
        }
    
    def get_text_splitter_config(self) -> Dict[str, Any]:
        """获取文本分割配置"""
        return {
            "chunk_size": self.text_splitter.chunk_size,
            "chunk_overlap": self.text_splitter.chunk_overlap,
            "splitter_name": self.text_splitter.splitter_name,
            "zh_title_enhance": self.text_splitter.zh_title_enhance,
        }


# 全局配置实例
settings = Settings() 